package leetcode.剑指offer;

import java.util.HashMap;
import java.util.Map;

class Solution {
    Map<Integer, Integer> inMap = new HashMap<>();

    public TreeNode buildTree(int[] preorder, int[] inorder) {
        int n = preorder.length;
        for (int i = 0; i < n; i++) {
            inMap.put(inorder[i], i);
        }
        return build(preorder, inorder, 0, n - 1, 0, n - 1);

    }

    public TreeNode build(int[] preorder, int[] inorder, int prel, int prer, int inl, int inr) {
        //不能用=符号，因为prel和prer当前都没用过
        if (prel > prer) return null;
        //构建根节点
        TreeNode root = new TreeNode(preorder[prel]);
        //在中序遍历中找到根节点的位置
        int po = inMap.get(preorder[prel]);
        //找到前序遍历root左节点还有多少个
        int leftNum = po - inl;
        root.left = build(preorder, inorder, prel + 1, prel + leftNum, inl, po - 1);
        root.right = build(preorder, inorder, prel + leftNum + 1, prer, po + 1, inr);
        return root;

    }
}